package com.efounder.form.action;

import com.alibaba.fastjson.JSONObject;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.common.TCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.model.JSONFormModel;
import com.efounder.form.util.JsonEFDataSetUtil;
import com.efounder.frame.baseui.EFActivity;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.ThreadManager;


/**
 * 单据保存
 *
 * @autor yqs
 * @date 2019/4/13 15:51
 **/
public class FormSaveAction extends ActionComponent {
    private String actionText;
    private String actionIcon;

    private JSONFormModel formModel;

    public JSONFormModel getFormModel() {
        return formModel;
    }

    public FormSaveAction setFormModel(JSONFormModel formModel) {
        this.formModel = formModel;
        return this;
    }

    @Override
    public void setActionText(String text) {
        actionText = text;
    }

    @Override
    public String getActionText() {
        return actionText;
    }

    @Override
    public void setActionIcon(String icon) {
        actionIcon = icon;
    }

    @Override
    public String getActionIcon() {
        return actionIcon;
    }


    @Override
    public void doAction() {

        if (formModel == null || formModel.getFormDataModel() == null || formModel.getFormDataModel().getBillDataSet() == null) {
            return;
        }
        //执行保存操作
        String GUID = (String) formModel.getDataContainer().getValue("GUID", "");
        String MDL_ID = (String) formModel.getDataContainer().getValue("MDL_ID", "");
        String FLOW_ID = (String) formModel.getDataContainer().getValue("FLOW_ID", "");
        String NODE_ID = (String) formModel.getDataContainer().getValue("NODE_ID", "");
        String Product = (String) formModel.getDataContainer().getValue("Product", "");

        com.alibaba.fastjson.JSONObject paramObject = new JSONObject();
        paramObject.put("MDL_ID", MDL_ID);
        paramObject.put("FLOW_ID", FLOW_ID);
        paramObject.put("NODE_ID", NODE_ID);
        paramObject.put("Product", Product);


        //        OSPTaskURL=https://cwyth-uat.cscec.com/OSPFlowCenter
        //"https://cwyth-uat.cscec.com/FIService/rest/load/loadform"
        String taskURL = EnvironmentVariable.getProperty("OSPTaskURL");
        if (taskURL.length() > 0) {
            taskURL = taskURL.substring(0, taskURL.lastIndexOf("/"));
            taskURL = taskURL + "/FIService/rest/save/createBill";
        }

        EFDataSet efDataSet = formModel.getFormDataModel().getBillDataSet();

        final com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        net.sf.json.JSONObject formData = JsonEFDataSetUtil.efDataSet2JSONObject(efDataSet);
        //放入GUID
        try {
            formData.getJSONObject("billDataSet").getJSONArray("rowSetArray").getJSONObject(0).getJSONObject("dataMap")
                    .put("F_GUID", GUID);
        } catch (Exception e) {
            e.printStackTrace();
        }

        jsonObject.put("formData", formData);
        jsonObject.put("params", paramObject);

        ((EFActivity) AppContext.getCurrentActivity()).showLoading("保存中...");
        TCommonRequestManager.getInstance(AppContext.getInstance()).requestPostByAsyncWithJSON(AppContext.getCurrentActivity().getClass().getSimpleName(),
                taskURL, jsonObject.toString(),
                new TCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(final String result) {
//                        ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                        // {"code":"0","data":{"responseObject":{"dataMap":{}},"MESS":"单据保存成功!
                        // \u003Cbr\u003E 流程初始出错：网络异常导致流程启用失败，请重新保存！","osplicense":"FALSE"}}
                        //数据量太大，必须放到线程中
                        final String topClassName = ActivityUtils.getTopActivity().getClass().getSimpleName();
                        ThreadManager.getThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    //net.sf 解析
//                                    long currentTime1 = System.currentTimeMillis();
//                                    net.sf.json.JSONObject jsonObject =  net.sf.json.JSONObject.fromObject(result);
//                                    long currentTime2 = System.currentTimeMillis();
//
//                                    org.json.JSONObject jsonObject1 = new org.json.JSONObject(result);
//                                    long currentTime3 = System.currentTimeMillis();
//                                    com.alibaba.fastjson.JSONObject jsonObject2 = JSON.parseObject(result);
//                                    long currentTime4 = System.currentTimeMillis();
//
//                                    System.out.println("net.sf.json 解析时间：" + (currentTime2 - currentTime1));
//                                    System.out.println(" org.json.JSONObject 解析时间：" + (currentTime3 - currentTime2));
//                                    System.out.println("fastjson 解析时间：" + (currentTime4 - currentTime3));


                                    org.json.JSONObject resultObject = new org.json.JSONObject(result);

                                    if ("0".equals(resultObject.getString("code"))) {
//                                ToastUtil.showToast(AppContext.getInstance(), resultObject.getJSONObject("data").getString("MESS"));
                                        formModel.getDataContainer().setValue("saveResult", result);
                                        ActivityUtils.getTopActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (ActivityUtils.getTopActivity().getClass().getSimpleName().equals(topClassName)) {
                                                    ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                                                    ToastUtil.showToast(AppContext.getInstance(), "单据保存成功");

                                                }
                                            }
                                        });

                                    } else {
                                        ActivityUtils.getTopActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (ActivityUtils.getTopActivity().getClass().getSimpleName().equals(topClassName)) {
                                                    ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                                                    ToastUtil.showToast(AppContext.getInstance(), "单据保存失败");
                                                }
                                            }
                                        });
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    ToastUtil.showToast(AppContext.getInstance(), "单据保存失败");
                                }
                            }
                        });


                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        ((EFActivity) AppContext.getCurrentActivity()).dismissLoading();
                        ToastUtil.showToast(AppContext.getInstance(), "保存失败");

                    }
                });

    }

    @Override
    public void doUpdate() {

    }


    @Override
    public String getID() {
        return null;
    }

    @Override
    public void setID(String id) {

    }

    @Override
    public void creationComplete() {

    }
}
